#include <QtScript>
#include <QyLexerFactory>
#include <QySciLexer>
#include <QyScript>

#include "QyLexerConfigurator.h"

/**************************************************************************************************/

class QyMultiLexerFactory : public QyLexerFactory {
public:
	QyMultiLexerFactory( const QString & fileFilter ) : QyLexerFactory(fileFilter)
		{ p_lexer = new QySciLexer(); }
	~QyMultiLexerFactory() { delete p_lexer; }

	QsciLexer * lexer() const { return p_lexer; }

private:
	QySciLexer * p_lexer;

};

/**************************************************************************************************/

QyLexerConfigurator::QyLexerConfigurator( QObject * parent ) : QObject(parent) {
}

QyLexerConfigurator::~QyLexerConfigurator() {

	QyLexerFactory::clear();

}

QObject * QyLexerConfigurator::lexer( const QString & fileFilter ) {

	QsciLexer * lexer = QyLexerFactory::lexerByFilefilter(fileFilter);

	if (!lexer) {

		QyMultiLexerFactory * newFactory = new QyMultiLexerFactory(fileFilter);

		lexer = newFactory->lexer();

	}

	return lexer;
}

void QyLexerConfigurator::applySettings( const QScriptValue & value ) {

	QMap<QString,QVariant> propertyMap;

	QyScript::generatePropertyMap( value, "", propertyMap );

	if ( value.isQObject() ) {

		if ( QySciLexer * lexer = dynamic_cast<QySciLexer *>( value.toQObject() ) ) {

			lexer->clearSettings();
			lexer->loadPropertyFromMap(propertyMap);

		} else
			qWarning( "Can't apply settings for not QySciLexer type." );

	} else
		qWarning( "Can't apply settings for unknow type." );

}
